
import router, { asyncRoutes } from "./router";
import { useUserStore } from "./stores/user";
import { ElMessage } from "element-plus";
import { getLocalToken } from "./utils/auth";
import { getProfileAPI } from "./apis/user";
import type { RouteRecordRaw } from "vue-router";
import { useMenuStore } from "./stores/menu";

// 根据权限标识过滤路由表
const getRoutes = (firstRoutePerms: string[], secondRoutePerms: string[], asyncRoutes: RouteRecordRaw[]) => {
  if(firstRoutePerms.includes('*')){
    return [...asyncRoutes]
  }
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  const firstRoutes = asyncRoutes.filter((route: RouteRecordRaw) => {
    return firstRoutePerms.includes(route.meta!.permission!)
  })
  console.log(firstRoutes)

  // 2. 对二级路由做过滤
  const perRoutes = firstRoutes.map((route: RouteRecordRaw) => {
    return {
      ...route,
      children: route!.children!.filter(v => secondRoutePerms.includes(v.meta!.permission!))
    }
  })
  // 3.保存侧边栏菜单路由
  const menuStore = useMenuStore()
  menuStore.setMenuList(perRoutes as RouteRecordRaw[])
  return perRoutes
}
// 创建白名单
const WHITE_LIST = ['/login','404']
// 处理一级路由数据

/**
* 处理一级路由数据
*/
const getFirstRoutePerms = (permsArr: string[]) => {
 const newArr = permsArr.map(item => {
   return item.split(':')[0]
 })
 return [...new Set(newArr)]
}

// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}
// 路由导航守卫
router.beforeEach( async (to,from,next)=>{
  // 非 vue 组件获取 store，在使用前才获取，避免 pinia 还没创建完成
  const token = getLocalToken()
  // 判断是否有token 
  const  store = useUserStore()
  if(store.token){
    next()
    if(!store.profile.id){
      const res = await getProfileAPI()
      store.setProfile(res.data)
      console.log('profile res', res);
      const menus = getFirstRoutePerms(res.data.permissions)
      const smenus = getSecondRoutePerms(res.data.permissions)
      // 1. 获取匹配的路由
      const perRoutes = getRoutes(menus, smenus, asyncRoutes)
// 4. 把动态路由表加入到路由系统中（当浏览器中访问路由的路径 显示渲染出来对应的组件）
        perRoutes.forEach(route => {
        	router.addRoute(route)
        })

        next({...to})
      
    } 
    next()
  }else{
    if(WHITE_LIST.includes(to.path)){
      // 在白名单内，路由放行
      next()
    }else{
      // 不在白名单内跳转至登录页
      next('/login')
      ElMessage.warning('登录信息无效,请先登录')
    }
  }
})

